<template>
  <div class="home">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <div class="search-input">
        <van-icon name="search" class="search-icon" />
        <input type="text" placeholder="请输入设备编号" v-model="deviceId" @keyup.enter="searchDevice" />
      </div>
      <van-button type="primary" size="small" @click="searchDevice">搜索</van-button>
    </div>

    <!-- 轮播图 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item>
        <img src="http://jiu.test.com/static/uploads/lunbo/1.png" alt="轮播图1" class="swiper-image" />
      </van-swipe-item>
      <van-swipe-item>
         <img src="http://jiu.test.com/static/uploads/lunbo/2.png" alt="轮播图1" class="swiper-image" />
      </van-swipe-item>
      <van-swipe-item>
         <img src="http://jiu.test.com/static/uploads/lunbo/3.png" alt="轮播图1" class="swiper-image" />
      </van-swipe-item>
      <van-swipe-item>
         <img src="http://jiu.test.com/static/uploads/lunbo/4.png" alt="轮播图1" class="swiper-image" />
      </van-swipe-item>      
    </van-swipe>

    <!-- 功能入口 -->
    <!--<div class="function-entry">
      <div class="entry-item" @click="goToPage('Login')">
        <van-icon name="user" size="40" color="#1989fa" />
        <span>登录/注册</span>
      </div>
      <div class="entry-item" @click="goToUserCenter">
        <van-icon name="user-circle" size="40" color="#1989fa" />
        <span>个人中心</span>
      </div>
      <div class="entry-item" @click="goToOrderList">
        <van-icon name="orders-o" size="40" color="#1989fa" />
        <span>我的订单</span>
      </div>
    </div>-->

    <!-- 店铺列表 -->
    <div class="shop-showcase">
      <div class="section-title">
        <h3>附近酒馆</h3>
        <span class="more" @click="refreshShops" v-if="!loading">刷新</span>
      </div>
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" color="#1989fa" />
        <span style="margin-left: 10px;">正在获取附近店铺...</span>
      </div>
      <div v-else-if="nearbyShops.length === 0" class="empty-container">
        <van-empty description="附近暂无店铺" />
      </div>
      <div v-else class="shop-list">
        <div 
          v-for="shop in nearbyShops" 
          :key="shop.shop_id" 
          class="shop-item" 
          @click="viewShop(shop.shop_id)"
        >
          <img :src="shop.shop_image || 'https://via.placeholder.com/150x150?text=酒馆'" :alt="shop.shop_name" class="shop-image" />
          <div class="shop-info">
            <h4>{{ shop.shop_name }}</h4>
            <p>{{ shop.address }}</p>
            <div class="shop-status">
              <span class="status" :class="shop.shop_status === 1 ? 'online' : 'offline'">
                {{ shop.shop_status === 1 ? '营业中' : '已休息' }}
              </span>
              <span class="distance">{{ shop.distance_text }}</span>
            </div>
            <div class="device-count" style="display:none">
              <span>设备数量: {{ shop.device_count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部提示 -->
    <div class="bottom-tips">
      <p>使用说明：</p>
      <ol>
        <!-- <li>输入设备编号或选择附近设备</li> -->
        <li>查看酒品信息并选择打酒数量</li>
        <li>完成支付后即可打酒</li>
      </ol>
    </div>
    <van-tabbar v-model="active" @change="onChange">
      <van-tabbar-item name="home" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item name="orders" icon="orders-o">订单</van-tabbar-item>
    </van-tabbar>    
  </div>
</template>

<script>
import { api, mockData } from '../api'
import { showToast } from 'vant'
import { Tabbar, TabbarItem } from 'vant';
// 方式二：在组件内按需引入
import { showNotify } from 'vant';
export default {
  name: 'Home',
  data() {
    return {
      active: 'home',
      deviceId: '',
      nearbyShops: [],
      loading: false,
      userLocation: {
        longitude: 116.407395, // 默认北京坐标
        latitude: 39.904211
      }
    }
  },
  mounted() {
    this.getUserLocation()
  },
  methods: {
     onChange(index) {
     if(index === 'orders'){
        this.$router.push('/order-list')
     }
    },
    // 获取用户位置
    getUserLocation() {
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.userLocation = {
              longitude: position.coords.longitude,
              latitude: position.coords.latitude
            }
            this.getNearbyShops()
          },
          (error) => {
            console.error('获取位置失败:', error)
            showToast('无法获取位置信息，使用默认位置')
            // 使用默认位置获取附近店铺
            this.getNearbyShops()
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 300000 // 5分钟缓存
          }
        )
      } else {
        showToast('浏览器不支持位置功能，使用默认位置')
        // 使用默认位置获取附近店铺
        this.getNearbyShops()
      }
    },

    // 获取附近店铺
    async getNearbyShops() {
      this.loading = true
      try {
        // 实际项目中应该调用真实API
        const res = await api.getShopsByLocation({
          longitude: this.userLocation.longitude,
          latitude: this.userLocation.latitude,
          radius: 1000,
          page: 1,
          page_size: 10
        })
        this.nearbyShops = res.data.list || []
        this.loading = false


        // 使用mock数据进行模拟
        // setTimeout(() => {
        //   this.nearbyShops = mockData.nearbyShops
        //   this.loading = false
        // }, 1000)
      } catch (error) {
        console.error('获取附近店铺失败:', error)
        showToast('获取附近店铺失败，请重试')
        // 使用mock数据作为兜底
        setTimeout(() => {
          this.nearbyShops = mockData.nearbyShops
          this.loading = false
        }, 500)
      }
    },

    // 刷新店铺列表
    refreshShops() {
      this.getUserLocation()
    },
    
    // 搜索设备
    async searchDevice() {
      if (!this.deviceId.trim()) {
        showToast('请输入设备编号')
        return
      }
      
      try {
        // 实际项目中应该调用真实API
        // const res = await api.getDeviceItemInfo({ device_id: this.deviceId })
        // this.$router.push({ name: 'DeviceInfo', params: { deviceId: this.deviceId } })
        
        // 使用mock数据进行模拟
        this.$router.push({ name: 'DeviceInfo', params: { deviceId: this.deviceId } })
      } catch (error) {
        showToast('设备不存在或已离线')
      }
    },
    
    // 查看店铺详情
    viewShop(shopId) {
      this.$router.push({ name: 'ShopDetail', params: { shopId } })
    },
    
    // 跳转到指定页面
    goToPage(pageName) {
      this.$router.push({ name: pageName })
    },
    
    // 跳转到个人中心
    goToUserCenter() {
      const token = localStorage.getItem('token')
      if (token) {
        this.$router.push({ name: 'User' })
      } else {
        this.$router.push({ name: 'Login' })
      }
    },
    
    // 跳转到订单列表
    goToOrderList() {
      const token = localStorage.getItem('token')
      if (token) {
        this.$router.push({ name: 'OrderList' })
      } else {
        this.$router.push({ name: 'Login' })
      }
    }
  }
}
</script>

<style scoped>
.home {
  padding-bottom: 60px;
}

.search-bar {
  display: flex;
  padding: 10px;
  background-color: #fff;
  align-items: center;
}

.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 0 15px;
  margin-right: 10px;
}

.search-icon {
  margin-right: 8px;
}

.search-input input {
  border: none;
  background: transparent;
  flex: 1;
  height: 36px;
  font-size: 14px;
}

.my-swipe {
  height: 150px;
  background-color: #f5f5f5;
}

.swiper-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.function-entry {
  display: flex;
  background-color: #fff;
  padding: 20px 0;
  margin-top: 10px;
}

.entry-item {
  flex: 1;
  text-align: center;
}

.entry-item span {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.shop-showcase {
  background-color: #fff;
  margin-top: 10px;
  padding: 15px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.more {
  font-size: 14px;
  color: #999;
}

.shop-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.shop-item {
  width: calc(50% - 7.5px);
  background-color: #f8f8f8;
  border-radius: 8px;
  overflow: hidden;
  padding: 10px;
}

.shop-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.shop-info {
  margin-top: 10px;
}

.shop-info h4 {
  margin: 0;
  font-size: 14px;
  font-weight: bold;
}

.shop-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.shop-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.online {
  background-color: #e1f3d8;
  color: #67c23a;
}

.offline {
  background-color: #f5f5f5;
  color: #909399;
}

.distance {
  font-size: 12px;
  color: #1989fa;
}

.device-count {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 0;
}

.empty-container {
  padding: 30px 0;
}

.bottom-tips {
  margin: 20px 15px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.bottom-tips p {
  margin: 0 0 10px 0;
  font-weight: bold;
  font-size: 14px;
}

.bottom-tips ol {
  margin: 0;
  padding-left: 20px;
}

.bottom-tips li {
  margin-bottom: 5px;
  font-size: 13px;
  color: #666;
}
</style>